"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : autocommit
Case Name   : 关闭自动提交后基本语句功能验证，create/alter/drop table 后提交/回滚
Create At   : 2023/01/17
@zou_jialiang0501162244
Description :
    1、开启session1连接B库，关闭自动提交，创建表1，等session2查询后提交，创建表2回滚，
       session2查询后删除表字段，提交
    2、开启session2查询表是否存在，session1提交后再查询，
       session1删除表字段提交前后desc查看表字段
    3、autocommit=0，重命名表，回滚前后查询
    4、清理环境
Expect      :
    1、建表成功
    2、执行成功
    3、回滚后查询新表名不存在
    4、成功
History     :
    modified by @zou_jialiang050 at 2023-8-15:增加用例等待时间
"""

import os
import time
import unittest

from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.ComThread import ComThread


class TestAutocommit(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.tb1_name = 't_autocommit_0029_1'
        self.tb2_name = 't_autocommit_0029_2'
        self.db_name = 'db_autocommit_0029'
        self.log.info("-----预置兼容B库-----")
        preset_db = f"drop database if exists {self.db_name};" \
                    f"create database {self.db_name} dbcompatibility 'B';"
        preset_db_res = self.pri_sh.execut_db_sql(preset_db)
        self.log.info(preset_db_res)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, preset_db_res,
                      f"创建兼容B库失败")

    def test_autocommit(self):
        text1 = '-----step1:开启session1连接B库，关闭自动提交，创建表1，' \
                '等session2查询后提交，创建表2回滚，session2查询后删除表字' \
                '段，提交;expect:建表成功-----'
        self.log.info(text1)
        sql1 = f"set autocommit to off;" \
               f"drop table if exists {self.tb1_name} cascade;" \
               f"create table {self.tb1_name}(col1 int, col2 int)" \
               f"partition by list(col1)(partition p1 values (2000)," \
               f"partition p2 values (3000),partition p3 values (4000)," \
               f"partition p4 values (5000));" \
               f"select pg_sleep(5); commit;" \
               f"drop table if exists {self.tb2_name} cascade;" \
               f"create table {self.tb2_name}(a int);" \
               f"rollback;" \
               f"select pg_sleep(5);" \
               f"alter table {self.tb1_name} drop column col2;" \
               f"select pg_sleep(5); commit;"
        session1 = ComThread(self.pri_sh.execut_db_sql,
                             args=(sql1, '', self.db_name))
        session1.setDaemon(True)

        text2 = '-----step2:开启session2查询表是否存在，session1提交后' \
                '再查询，session1删除表字段提交前后desc查看表字段;' \
                'expect:执行成功-----'
        self.log.info(text2)
        sql2 = f"select * from pg_tables where tablename='{self.tb1_name}';" \
               f"select pg_sleep(5);" \
               f"select * from pg_tables where tablename " \
               f"in ('{self.tb1_name}', '{self.tb2_name}');" \
               f"select pg_sleep(5);desc {self.tb1_name};" \
               f"select pg_sleep(5);desc {self.tb1_name};"
        session2 = ComThread(self.pri_sh.execut_db_sql,
                             args=(sql2, '', self.db_name))
        session2.setDaemon(True)
        # 先后启动线程，间隔1s
        session1.start()
        time.sleep(3)
        session2.start()
        session1.join(10)
        session2.join(10)
        result1 = session1.get_result()
        self.log.info(f'session1_results: {result1}')
        result2 = session2.get_result()
        self.log.info(f'session2_results: {result2}')
        self.assertIn('SET', result1, f"关闭自动提交失败: {text1}")
        self.assertEqual(result1.count(self.constant.CREATE_TABLE_SUCCESS), 2,
                         f"执行失败: {text1}")
        self.assertEqual(result1.count(self.constant.COMMIT_SUCCESS_MSG), 2,
                         f"提交事务失败: {text1}")
        self.assertIn(self.constant.ROLLBACK_MSG, result1, f"执行失败{text1}")
        self.assertIn(self.constant.ALTER_TABLE_MSG, result1, f"执行失败{text1}")
        self.assertEqual(result2.splitlines()[2].strip(),
                         '(0 rows)', f"执行失败{text2}")
        self.assertIn(self.tb1_name, result2.splitlines()[11],
                      f"执行失败{text2}")
        self.assertEqual(result2.count('col2'), 1, f"执行失败{text2}")

        text3 = '-----step3:autocommit=0，重命名表，回滚，查询新表名不存在;' \
                'expect:执行成功-----'
        self.log.info(text3)
        sql = f"set autocommit=0;" \
              f"alter table {self.tb1_name} rename to {self.tb1_name}_new;" \
              f"select tablename from pg_tables where tablename " \
              f"in ('{self.tb1_name}', '{self.tb1_name}_new');" \
              f"rollback;" \
              f"select tablename from pg_tables where tablename " \
              f"in ('{self.tb1_name}', '{self.tb1_name}_new');;"
        sql_res = self.pri_sh.execut_db_sql(sql, '', self.db_name)
        self.log.info(sql_res)
        self.assertIn(f"{self.tb1_name}_new", sql_res.splitlines()[4],
                      f"执行失败: {text3}")
        self.assertIn(self.constant.ALTER_TABLE_MSG, sql_res, f"执行失败: {text3}")
        self.assertIn(self.constant.ROLLBACK_MSG, sql_res, f"执行失败: {text3}")
        self.assertEqual(self.tb1_name, sql_res.splitlines()[-2].strip(),
                         f"执行失败: {text3}")

    def tearDown(self):
        text4 = '-----step4:清理环境 expect:成功-----'
        self.log.info(text4)
        drop_db_res = self.pri_sh.execut_db_sql(
            f"drop database if exists {self.db_name};")
        self.log.info(drop_db_res)
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, drop_db_res,
                      f"执行失败: {text4}")
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
